<template>
  <div class="container-content cluster">
    <div class="content-heard">
      <div class="user-info">
        <a-dropdown :trigger="['click','hover']">
          <a class="ant-dropdown-link" @click="e => e.preventDefault()">
            {{loginName}}
            <a-icon type="down" />
          </a>
          <a-menu slot="overlay" class="sys-opts">
            <a-menu-item @click="logout" key="0">退出</a-menu-item>
          </a-menu>
        </a-dropdown>
      </div>
      <div class="user-ico">
        <img src="../../assets/images/head-img.png" alt />
      </div>
      <div class="title">
        <p>用户运营管理系统</p>
      </div>
    </div>
    <div class="content-box">
      <div class="product-list">
        <span class="product-title">产品服务到期情况</span>
        <div class="product-list-content">
          <div class="overflow-container">
            <ul
              ref="ulContant"
              :style="{ transform: 'translateX' + '(' + currentOffset + 'px' + ')'}"
            >
              <li v-for="(item) in options" :key="item.id">
                <selectDate :productDate="item.expire" :productTitle="item.name" v-if="show">
                  <slot>
                    <span></span>
                  </slot>
                </selectDate>
              </li>
            </ul>
          </div>
          <div class="swiper-button-next" :disabled="atHeadOfList" @click="moveCarousel(-1)">
            <i class="iconfont iconleft"></i>
          </div>
          <div class="swiper-button-prev" @click="moveCarousel(1)" :disabled="atEndOfList">
            <i class="iconfont iconright"></i>
          </div>
        </div>
      </div>
      <div class="user-management">
        <div class="content-title">
          <p>用户管理</p>
        </div>
        <div class="user-management-content">
          <div class="left-content">
            <groupManagement
              :isShowAddBtn="true"
              :groupList="groupList"
              @deleteList="deleteList"
              @itemClick="itemClick"
              @saveList="saveList"
              v-if="groupShow"
            >
              <span slot="title">群组管理</span>
              <a-icon slot="ico" type="user" />
            </groupManagement>
          </div>
          <div class="right-content">
            <div class="formDiv">
              <a-form layout="inline">
                <a-form-item>
                  <a-input v-model="keywords" type="text" style="width: 180px;" />
                </a-form-item>
                <a-form-item>
                  <a-button type="primary" @click="userSearch">搜索</a-button>
                </a-form-item>
                <a-form-item>
                  <a-button @click="userSearchReset">重置</a-button>
                </a-form-item>
              </a-form>
              <div class="operation-btn">
                <a-button type="primary" @click="userAdd()">新增</a-button>
                <!-- <a-button @click="selectGroup()">转移群组</a-button> -->
                <a-button type="danger" @click="userBatchDelete()">删除</a-button>
              </div>
            </div>
            <div class="user-table" style="margin-top:10px">
              <a-table
                :row-selection="{ selectedRowKeys: userSelectedRowKeys, onChange: onSelectChange }"
                :columns="userColumns"
                :data-source="userList"
                rowKey="id"
                :pagination="pagination"
                @change="userChangePage"
              >
                <template slot-scope="text,record" slot="userAction">
                  <a class="tools" @click="userEdit(record)">编辑</a>
                  <a class="tools" @click="selectGroup(record)">转移群组</a>
                  <!-- <a class="tools" @click="enableUser(record)" v-if="record.flag!='0'">启用</a>
                  <a class="tools" @click="disableUser(record)" v-if="record.flag=='0'">禁用</a> -->
                  <a class="tools" type="link" @click="userDelete(record)">删除</a>
                  <a class="tools" @click="resetPassword(record)">重置密码</a>
                </template>
                <template slot-scope="text,record" slot="flag">
                  <!-- <a-badge :color="record.flag===0?'#87d068':'#f50'" :text="record.flag|userStatus"></a-badge> -->
                  <a-switch
                      checked-children="启用"
                      un-checked-children="锁定"
                      @change="(checked) => onChange(checked, record)"
                      :checked="record.flag == 0"
                    />
                </template>
              </a-table>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="modal-content">
      <!-- 新增编辑弹框 -->
      <userOperation
        :id="unitId"
        :userId="userId"
        :optFlag="optFlag"
        :modalTitle="modalTitle"
        :userOperationVisible="userOperationVisible"
        @updateUserInform="updateUserInform"
        @closeFunc="userOperationVisible=false"
      ></userOperation>
      <selectGroup
        :id="userId"
        :groupId="groupId"
        :selectGroupVisible="selectGroupVisible"
        @updateUserGroup="updateUserGroup"
        @closeFunc="selectGroupVisible=false"
      ></selectGroup>
    </div>
  </div>
</template>

<script>
import groupManagement from "components/base/groupManagement";
import selectDate from "components/base/selectDate";
import userOperation from "components/general/userOperation";
import selectGroup from "components/general/selectGroup";
import { paging } from "assets/js/mixin";
import { commonUser } from "@/api/commonUser";
import { unitOperation, members, user } from "@/api/user";
import { outlogin} from "api/login";
export default {
  mixins: [paging],
  components: {
    groupManagement,
    selectDate,
    userOperation,
    selectGroup
  },
  data() {
    return {
      //用户名
      loginName: "",
      keywords: "",
      show: false,
      options: [],
      dropdownVisible: false,
      userSelectedRowKeys: [],
      groupList: [],
      userColumns: [
        {
          title: "用户名",
          dataIndex: "loginName",
          scopedSlots: { customRender: "loginName" }
        },
        {
          title: "手机号",
          dataIndex: "mobile"
        },
        {
          title: "邮箱",
          dataIndex: "email"
        },
        {
          title: "申请时间",
          dataIndex: "applyTime"
        },
        {
          title: "群组信息",
          dataIndex: "unitName"
        },
        {
          title: "状态",
          width: 120,
          dataIndex: "flag",
          scopedSlots: { customRender: "flag" }
        },
        {
          title: "操作",
          dataIndex: "userAction",
          width: 280,
          align: "center",
          scopedSlots: { customRender: "userAction" }
        }
      ],
      userList: [],
      //弹框显示
      userOperationVisible: false,
      modalTitle: "新增用户",
      optFlag: 1,
      //转移群组
      selectGroupVisible: false,
      //轮播
      pageWidth: 0,
      currentOffset: 0,
      ulWidth: 0,
      windowSize: 0,
      liWidth: 0,
      unitId: "",
      groupId: "",
      userId: "",
      groupShow: false,
      numbers: 0
    };
  },
  mounted() {
    this.loginName = JSON.parse(localStorage.getItem("userInfo")).cname;
    this.unitId = JSON.parse(localStorage.getItem("userInfo")).rootId;
    this.getUserService();
    this.getGroupList();
    this.$once("hook:beforeDestroy", () => {
      window.removeEventListener("resize", this.getWidth());
    });
  },
  watch: {
    show() {
      //首次进入获取不到宽度，监听show数据改变判断数据是否加载
      this.getWidth();
      window.onresize = () => {
        this.getWidth();
      };
    }
  },
  computed: {
    atEndOfList() {
      return (
        this.currentOffset <=
        this.liWidth * -1 * (this.options.length - this.windowSize)
      );
    },
    atHeadOfList() {
      return this.currentOffset === 0;
    }
  },
  methods: {
    //获取产品服务
    getUserService() {
      this.show = false;
      commonUser
        .getCommonService()
        .then(res => {
          console.log(res.data.data)
          if(res.data.data===null){
            return
          }else{
            this.options = res.data.data;
            this.show = true;
          }
        })
        .catch(err => {
          this.$message.destroy();
          this.$message.error(err);
        });
    },
    //获取群组列表
    getGroupList() {
      this.groupShow = false;
      commonUser
        .getGroupList()
        .then(res => {
          this.groupList = res.data.data;
          if(this.groupList.length !==0){
            this.groupList.forEach((item) => {
              //数据新增属性页面不刷新
              this.$set(item, "isEdit", false);
            });
          }else {
            this.groupId = ''
            this.groupList = []
          }
          this.getUserList(this.groupId)
          this.groupShow = true;
        })
        .catch(err => {
          console.log(err.response)
          this.$message.destroy();
          this.$message.error(err);
        });
    },
    //更新群组名称操作
    saveList(val) {
      var param
      if (val.type === "edit") {
        param = {
          id: val.grouplist.id,
          unitName: val.grouplist.unitName
        };
        unitOperation
          .updateUnitName(param)
          .then(() => {
            this.$message.destroy();
            this.$message.success("操作成功");
            this.getGroupList();
          })
          .catch(err => {
            this.$message.destroy();
            this.$message.error(err);
            this.getGroupList();
          });
      } else {
        param = {
          unitName: val.grouplist.unitName
        };
        unitOperation
          .addUnitName(param)
          .then(() => {
            this.$message.destroy();
            this.$message.success("操作成功");
            this.getGroupList();
          })
          .catch(err => {
            this.$message.destroy();
            this.$message.error(err);
            this.getGroupList();
          });
      }
    },
    //删除群组
    deleteList(param) {
      var paramArr = [];
      paramArr.push(param.id);
      unitOperation
        .delete(paramArr)
        .then(() => {
          this.$message.destroy();
          this.$message.success("操作成功");
          this.getGroupList();
        })
        .catch(err => {
          this.$message.destroy();
            this.$message.error(err);
        });
    },
    //点击获取成员列表
    itemClick(val) {
      console.log(val)
      if (null != val) {
        this.groupId = val.id;
        this.getUserList(val.id);
      }
    },
    //转移群组更新
    updateUserGroup() {
      this.selectGroupVisible = false;
      this.getUserList(this.groupId);
    },
    getUserList(id) {
      var param = {
        unitId: id,
        searchVo: {
          current: this.pageNum,
          filterColumns: [],
          searchWord: this.keywords,
          size: this.pageSize
        }
      };
      commonUser
        .getUserList(param)
        .then(res => {
          this.userList = res.data.data.records;
          console.log(res);
        })
        .catch(err => {
          this.$message.destroy();
          this.$message.error(err);
        });
    },
    onChange(checked, record) {
      var _this = this;
      this.$confirm({
        title: record.flag == 1 ? "是否启用该用户？" : "是否锁定该用户？",
        okText: "确定",
        okType: "danger",
        cancelText: "取消",
        onOk() {
          if (checked) {
            record.flag = 0;
            _this.enableUser(record);
          } else {
            record.flag = 1;
            _this.disableUser(record);
          }
        },
      });
    },
    enableUser(record) {
      //启用
      var param = {
        ids: record.id,
        status: "enable"
      };
      user
        .disableUser(param)
        .then(() => {
          this.$message.destroy();
          this.$message.success("启用成功~");
          this.getUserList(this.groupId);
        })
        .catch(err => {
          this.$message.destroy();
          this.$message.error(err);
        });
    },
    disableUser(record) {
      //禁用
      var param = {
        ids: record.id,
        status: "disable"
      };
      user
        .disableUser(param)
        .then(() => {
          this.$message.destroy();
          this.$message.success("禁用成功~");
          this.getUserList(this.groupId);
        })
        .catch(err => {
          this.$message.destroy();
          this.$message.error(err);
        });
    },
    //重置密码
    resetPassword(record) {
      var param = [record.id];
      var _this = this;
      this.$confirm({
        title: "是否确认重置密码？",
        okText: "确定",
        okType: "danger",
        cancelText: "取消",
        onOk() {
          members
            .resetPassword(param)
            .then(res => {
              _this.$message.destroy();
              _this.$message.success(res.data.msg);
            })
            .catch(err => {
              _this.$message.destroy();
              _this.$message.error(err);
            })
            .finally(() => {});
        }
      });
    },
    moveCarousel(direction) {
      if (direction === 1 && !this.atEndOfList) {
        this.currentOffset -= this.liWidth;
      } else if (direction === -1 && !this.atHeadOfList) {
        this.currentOffset += this.liWidth;
      }
    },
    getWidth() {
      this.$nextTick(() => {
        this.ulWidth = this.$refs.ulContant.offsetWidth;
        this.pageWidth =
          (this.$refs.ulContant.children[0].offsetWidth + 35) *
          this.$refs.ulContant.children.length;
        this.liWidth = this.$refs.ulContant.children[0].offsetWidth + 35;
        this.windowSize = Math.floor(this.ulWidth / this.liWidth);
      });
    },
    logout() {
      outlogin().then((res)=>{
        //登出
        localStorage.removeItem("TOKEN");
        localStorage.removeItem("refreshToken");
        localStorage.removeItem("userInfo");
        localStorage.removeItem("permission");
        this.$router.push("/login");
        this.$message.destroy();
        this.$message.success(res.msg)
      }).catch((err)=>{
          this.$message.destroy();
            this.$message.error(err);
      })
    },
    onSelectChange(val) {
      this.userSelectedRowKeys = val;
    },
    //用户分页操作
    userChangePage(pagination) {
      this.userPageNum = pagination.current;
      this.userPagination.current = pagination.current;
      this.userPagination.pageSize = pagination.pageSize;
      this.getUserList(this.groupId);
    },
    //普通用户搜索
    userSearch() {
      this.userPageNum = 1;
      this.userPagination.current = 1;
      this.getUserList(this.groupId);
    },
    //普通用户重置
    userSearchReset() {
      this.keywords = "";
      this.userPageNum = 1;
      this.userPagination.current = 1;
      this.getUserList(this.groupId);
    },
    userAdd() {
      //用户新增
      console.log(this.unitId);
      this.userOperationVisible = true;
      this.modalTitle = "新增用户";
      this.optFlag = 1;
    },
    userEdit(records) {
      //用户编辑
      this.userOperationVisible = true;
      this.modalTitle = "用户编辑";
      this.optFlag = 2;
      this.userId = records.id;
    },
    updateUserInform() {
      this.userOperationVisible = false;
      this.getUserList(this.groupId);
    },
    selectGroup(records) {
      this.selectGroupVisible = true;
      this.userId = records.id;
    },
    userBatchDelete() {
      //用户批量删除
      console.log(this.userSelectedRowKeys);
      if (this.userSelectedRowKeys.length === 0) {
        this.$message.destroy();
        this.$message.warning("请选择需要删除的数据");
      } else {
        this.numbers = this.userSelectedRowKeys.length;
        var _this = this;
        this.$confirm({
          title: "确定要删除" + _this.numbers + "条记录吗？",
          okText: "确定",
          okType: "danger",
          cancelText: "取消",
          onOk() {
            members
              .delete(_this.userSelectedRowKeys)
              .then(() => {
                _this.$message.destroy();
                _this.$message.success("操作成功");
                _this.getUserList(_this.groupId);
              })
              .catch(err => {
                _this.$message.destroy();
                _this.$message.error(err);
              })
              .finally(() => {});
          }
        });
      }
    },
    //用户删除
    userDelete(record) {
      var _this = this;
      var param = [record.id];
      this.$confirm({
        title: "您是否确认要删除所选中的记录？",
        okText: "确定",
        okType: "danger",
        cancelText: "取消",
        onOk() {
          members
            .delete(param)
            .then(res => {
              _this.$message.destroy();
              _this.$message.success(res.data.msg);
              _this.getUserList(_this.groupId);
            })
            .catch(err => {
              _this.$message.destroy();
              _this.$message.error(err);
            })
            .finally(() => {});
        }
      });
    }
  },
  destroyed() {
    window.onresize = null;
  }
};
</script>

<style lang="stylus" scoped>
.container-content {
  background: #f3f3f9;
  height: 100%;
  width: 100%;

  .content-box {
    padding: 0 15px;
    box-sizing: border-box;
    height: calc(100% - 83px);
    overflow: hidden;

    .product-list {
      width: 100%;
      height: 116px;
      background: #ffffff;
      padding: 0 10px;
      box-sizing: border-box;
      margin-bottom: 10px;
      display: flex;
      align-items: center;

      .product-title {
        font-size: 16px;
        color: #333;
        display: inline-block;
        width: 100px;
        padding: 15px;
        background: #f5f5f5;
        line-height: 1.2;
        border-radius: 5px;
      }

      .product-list-content {
        width: 100%;
        padding: 0 70px;
        position: relative;
        overflow: hidden;

        .overflow-container {
          overflow: hidden;
        }

        ul {
          padding: 10px 0;
          white-space: nowrap;
          transform: 1500ms ease-out;
        }

        .swiper-button-next {
          position: absolute;
          left: 20px;
          top: 32px;
          cursor: pointer;

          i {
            font-size: 24px;
            color: #1890ff;
          }
        }

        .swiper-button-prev {
          position: absolute;
          right: 20px;
          top: 32px;
          cursor: pointer;

          i {
            font-size: 24px;
            color: #1890ff;
          }
        }

        div[disabled] {
          i {
            color: #c6c6c6;
          }
        }
      }
    }

    .user-management {
      background: #ffffff;
      height: calc(100% - 126px);

      .content-title {
        padding-left: 20px;
        border-bottom: 1px solid #ededed;
        margin-bottom: 10px;

        p {
          height: 44px;
          line-height: 44px;
          font-size: 16px;
          color: #666;
        }
      }

      .user-management-content {
        height: 100%;
        padding: 0 10px;
        box-sizing: border-box;

        .left-content {
          float: left;
          width: 320px;
          height: 100%;
          padding: 15px 0px 15px 10px;
          box-sizing: border-box;
          background: #f3f4f9;
          overflow: hidden;
        }

        .right-content {
          margin-left: 320px;
          padding: 0px 0px 10px 25px;
          height: 100%;
          box-sizing: border-box;
          position: relative;
          overflow-y: auto;
        }

        .formDiv {
          position: relative;
        }

        .operation-btn {
          position: absolute;
          top: 0;
          right: 0;

          button {
            margin-left: 10px;
          }
        }
      }
    }
  }
}

.content-heard {
  width: 100%;
  height: 83px;
  line-height: 83px;
  background: url('../../assets/images/common-bg.png') no-repeat;
  background-size: contain;
  padding-right: 20px;
  position: relative;
}

.title {
  position: absolute;
  height: 83px;
  line-height: 60px;
  width: 100%;
  text-align: center;
  font-size: 23px;
  font-weight: bold;
  color: #ffffff;
  text-shadow: 0 2px 9px #9cadbd
}

.user-info {
  position: absolute;
  right: 20px;
  width: 85px;
  z-index: 99;
  line-height: 57px;

  p {
    cursor: pointer;
  }
}

.user-ico {
  font-size: 0;
  width: 30px;
  height: 30px;
  margin-right: 15px;
  margin-top: 3px;
  position: absolute;
  right: 100px;

  img {
    width: 100%;
    height: 100%;
  }
}
</style>